package shop;

import commodity.Commodity;

import java.io.*;
import java.math.BigDecimal;
import java.util.HashMap;

//购物车
public class ShoppingCart {
    private HashMap<Commodity,Integer> shoppingCartHashMap=new HashMap<>();        //哈希容器，前者是商品，后者是数量

    public HashMap<Commodity, Integer> getShoppingCartHashMap() {
        return shoppingCartHashMap;
    }


    //读入商城商品
    public void read()
    {
        shoppingCartHashMap.clear();
        // BufferedReader br = null;
        try {
            String path = "resource/ShoppingCart.txt";

//            path = path.replace("file:/", "");
//            path = path.replace("/", "//");
            File file=new File(path);
            FileReader fr=new FileReader(file.getAbsoluteFile());
            BufferedReader br = new BufferedReader(fr);
            // br = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
            String data = null;
            while(true){
                try {
                    if (((data = br.readLine())==null)) {
                        br.close();
                        return;
                    }
                    String dataSplit[] = data.split("\\s+");
                    Commodity commodity=Mall.isExistCommodity(dataSplit[0]);
                    shoppingCartHashMap.put(commodity,Integer.parseInt(dataSplit[2]));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    //写入文件
    public void writeCommodity()
    {
        try {
            String path = "resource/ShoppingCart.txt";
            File file=new File(path);
            FileWriter fw = new FileWriter(file.getAbsoluteFile());//file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            for(Commodity commodity:shoppingCartHashMap.keySet()){
                String data=commodity.getName()+" "+Main.df.format(commodity.getPrice())+" "+shoppingCartHashMap.get(commodity);
                bw.write(data+"\n");
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //将num个商品加入购物车
    public void addCommodity(String commodityName,int num)
    {
        Commodity commodity=Mall.isExistCommodity(commodityName);
        if(commodity==null) {
            System.out.println("该商品不存在");
        } else {
            if(Mall.isOutOfStock(commodityName,num)){
                System.out.println(commodityName+"  购买数量超出库存！");
            }else {
                shoppingCartHashMap.merge(commodity, num, Integer::sum);
                System.out.println("添加成功");
                //merge()它将新的值赋值到 key (如果不存在)或更新给定的key 值对应的 value,最后的是remappingFunction，返回参数总和
            }
        }
        writeCommodity();
    }
//    public void reduceCommodity(Commodity commodity,int num)
//    {
//        if(!shoppingCartHashMap.containsKey(commodity)){
//            System.out.println();
//        }
//    }
    //将商品移除购物车
    public void removeCommodity()
    {
       // read();
        showShoppingCart();
        System.out.println("请输入需要删除的商品");
        String commodityName=Main.scanner.nextLine();
        Commodity commodity=isExistCommodity(commodityName);
        if(commodity==null) {
            System.out.println("该商品不存在");
        } else {
            shoppingCartHashMap.remove(commodity);
            System.out.println("删除成功");
        }
        writeCommodity();
    }


    //是否存在商品，有则返回该商品
    public Commodity isExistCommodity(String commodityName)
    {
        //read();
        for (Commodity commodity:shoppingCartHashMap.keySet()) {
            if(commodity.getName().equals(commodityName)){
                //System.out.println(commodity);
                return commodity;
            }
        }
        return null;
    }

    public void payTheBill(){
        //read();
        for (Commodity commodity: shoppingCartHashMap.keySet()) {
            Mall.setMallHashMap(commodity.getName(), shoppingCartHashMap.get(commodity));
        }
        shoppingCartHashMap.clear();
        // writeCommodity();
        // Main.mall.writeCommodity();

    }



    //展示购物车
    public void showShoppingCart(){
        //read();
        for (Commodity commodity : shoppingCartHashMap.keySet()) {
            System.out.println("商品名称："+commodity.getName()+" 商品单价："+Main.df.format(commodity.getPrice())
                    +" 商品数量："+shoppingCartHashMap.get(commodity));
        }
        System.out.println("商品总价："+Main.df.format(getPrice())+"元");
    }
    //计算商品总价
    public BigDecimal getPrice()
    {
        BigDecimal sum= BigDecimal.valueOf(0);
        for (Commodity commodity: shoppingCartHashMap.keySet()) {
            sum.add(commodity.getPrice().multiply(BigDecimal.valueOf(shoppingCartHashMap.get(commodity))));   //单价*键值（即数量）
        }
        return sum;
    }

    //清空购物车
    public void clearShoppingCart(){
        shoppingCartHashMap.clear();
    }
}
